package com.risk.management.service.impl;

import com.risk.management.entity.Project;
import com.risk.management.mapper.ProjectMapper;
import com.risk.management.service.ProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 项目服务实现类
 */
@Service
public class ProjectServiceImpl implements ProjectService {

    @Autowired
    private ProjectMapper projectMapper;

    @Override
    public Project getProjectById(Long id) {
        return projectMapper.selectById(id);
    }

    @Override
    public List<Project> getAllProjects() {
        return projectMapper.selectAll();
    }

    @Override
    public List<Project> getProjectsByManagerId(Long managerId) {
        return projectMapper.selectByManagerId(managerId);
    }

    @Override
    public List<Project> getProjectsByStatus(Integer status) {
        return projectMapper.selectByStatus(status);
    }

    @Override
    @Transactional
    public boolean addProject(Project project) {
        // 设置创建和更新时间
        Date now = new Date();
        project.setCreateTime(now);
        project.setUpdateTime(now);
        
        // 如果状态为空，设置为未开始状态
        if (project.getStatus() == null) {
            project.setStatus(1); // 1表示未开始
        }
        
        return projectMapper.insert(project) > 0;
    }

    @Override
    @Transactional
    public boolean updateProject(Project project) {
        // 检查项目是否存在
        Project existingProject = getProjectById(project.getId());
        if (existingProject == null) {
            return false;
        }
        
        // 设置更新时间
        project.setUpdateTime(new Date());
        
        return projectMapper.update(project) > 0;
    }

    @Override
    @Transactional
    public boolean deleteProject(Long id) {
        // 检查项目是否存在
        Project project = getProjectById(id);
        if (project == null) {
            return false;
        }
        
        return projectMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional
    public boolean updateProjectStatus(Long id, Integer status) {
        // 检查项目是否存在
        Project project = getProjectById(id);
        if (project == null) {
            return false;
        }
        
        // 检查状态是否有效（1-未开始，2-进行中，3-已完成，4-已取消）
        if (status < 1 || status > 4) {
            return false;
        }
        
        return projectMapper.updateStatus(id, status) > 0;
    }
} 